package service

import (
	"StrayAnimals/internal/initConfig"
	"StrayAnimals/internal/model"
	"database/sql"
	"errors"
	"go.uber.org/zap"
)

// CreateNewAnimal 添加动物到数据库
func CreateNewAnimal(newAnimal model.AnimalsInformation) error {
	err := initConfig.GormDb.Create(&newAnimal).Error
	if err != nil {
		zap.L().Error("无法把动物信息添加到数据库中", zap.Error(err))
		return err
	}
	return nil
}

// GetAnimalByIdFromSQL 手动执行 SQL 脚本获取单个动物
func GetAnimalByIdFromSQL(animalId string) (model.AnimalDetailResponse, error) {
	var response model.AnimalDetailResponse
	query := `
		SELECT id, name, age, type, uploaded_at, information, picture1, picture2, picture3, uploader_id, is_adopted
		FROM animals_information
		WHERE id = ?
	`
	err := initConfig.SqlDb.QueryRow(query, animalId).Scan(
		&response.ID,
		&response.Name,
		&response.Age,
		&response.Type,
		&response.UploadedAt,
		&response.Information,
		&response.Picture1,
		&response.Picture2,
		&response.Picture3,
		&response.UploaderID,
		&response.IsAdopted,
	)
	if err != nil {
		zap.L().Error("在animals_information表中查找失败" + err.Error())
		return response, err
	}

	// 查找上传者的姓名和电话
	var uploaderQuery = `
		SELECT username, phone 
		FROM user
		WHERE id = ?
	`
	var username string
	var phone string
	err = initConfig.SqlDb.QueryRow(uploaderQuery, response.UploaderID).Scan(&username, &phone)
	if err != nil {
		zap.L().Error("在user表中查找失败" + err.Error())
		return response, err
	} else {
		response.UploaderName = username
		response.UploaderPhone = phone
	}

	if response.IsAdopted {
		var adoptionQuery = `
			SELECT adopter_id, adoption_at 
			FROM adoption 
			WHERE animal_id = ?
		`
		var adopterID string
		var adoptionDate string
		err = initConfig.SqlDb.QueryRow(adoptionQuery, animalId).Scan(&adopterID, &adoptionDate)
		if err != nil {
			zap.L().Error("在adoption表中查找失败" + err.Error())
			return response, err
		}

		response.AdopterID = adopterID
		response.AdoptionDate = adoptionDate

		// 查找领养者的姓名和电话
		var AdopterQuery = `
			SELECT username, phone 
			FROM user 
			WHERE id = ?
		`
		var adopterName string
		var adopterPhone string
		err = initConfig.SqlDb.QueryRow(AdopterQuery, adopterID).Scan(&adopterName, &adopterPhone)
		if err != nil {
			zap.L().Error("在user表中查找失败" + err.Error())
			return response, err
		}

		response.AdopterName = adopterName
		response.AdopterPhone = adopterPhone
	}

	return response, nil
}

// GetAnimalListFromSQL 手动执行 SQL 脚本获取动物列表
func GetAnimalListFromSQL() ([]model.AnimalDetailResponse, error) {
	var animals []model.AnimalDetailResponse

	// 获取所有动物的基本信息
	query := `
		SELECT id, name, age, type, uploaded_at, uploader_id, information, picture1, picture2, picture3, is_adopted
		FROM animals_information
		ORDER BY uploaded_at DESC
	`
	rows, err := initConfig.SqlDb.Query(query)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	for rows.Next() {
		var animal model.AnimalDetailResponse
		err := rows.Scan(
			&animal.ID,
			&animal.Name,
			&animal.Age,
			&animal.Type,
			&animal.UploadedAt,
			&animal.UploaderID,
			&animal.Information,
			&animal.Picture1,
			&animal.Picture2,
			&animal.Picture3,
			&animal.IsAdopted,
		)
		if err != nil {
			zap.L().Error("Error scanning row" + err.Error())
			continue // 或者选择在这里返回错误
		}

		// 查找上传者的姓名和电话
		var uploaderQuery = `
		SELECT username, phone 
		FROM user
		WHERE id = ?
	`
		var username string
		var phone string
		err = initConfig.SqlDb.QueryRow(uploaderQuery, animal.UploaderID).Scan(&username, &phone)
		if err != nil {
			zap.L().Error("在user表中查找失败" + err.Error())
			return nil, err
		} else {
			animal.UploaderName = username
			animal.UploaderPhone = phone
		}

		// 如果该动物已被领养，则查询领养信息
		if animal.IsAdopted {
			var adoptionQuery = `
				SELECT adopter_id, adoption_at 
				FROM adoption 
				WHERE animal_id = ?
			`
			var adopterID string
			var adoptionDate string
			err = initConfig.SqlDb.QueryRow(adoptionQuery, animal.ID).Scan(&adopterID, &adoptionDate)
			if err != nil && !errors.Is(err, sql.ErrNoRows) { // 如果没有对应的领养记录，忽略错误
				zap.L().Error("Error querying adoption info", zap.Error(err))
				return nil, err
			} else if err == nil {
				animal.AdopterID = adopterID
				animal.AdoptionDate = adoptionDate

				// 查找领养者的姓名和电话
				var userQuery = `
					SELECT username, phone 
					FROM user 
					WHERE id = ?
				`
				var adopterName string
				var adopterPhone string
				err = initConfig.SqlDb.QueryRow(userQuery, adopterID).Scan(&adopterName, &adopterPhone)
				if err != nil && !errors.Is(err, sql.ErrNoRows) { // 如果没有找到用户信息，忽略错误
					zap.L().Error("Error querying user info", zap.Error(err))
					return nil, err
				} else if err == nil {
					animal.AdopterName = adopterName
					animal.AdopterPhone = adopterPhone
				}
			}
		}

		animals = append(animals, animal)
	}

	// 检查遍历过程中是否有错误
	if err = rows.Err(); err != nil {
		return nil, err
	}

	return animals, nil
}

func GetAnimalById(animalId string) (*model.AnimalsInformation, error) {
	var animal model.AnimalsInformation
	err := initConfig.GormDb.Where("id = ?", animalId).First(&animal).Error
	if err != nil {
		zap.L().Error("无法找到该动物", zap.Error(err))
		return nil, err
	}
	return &animal, nil
}

// CreateNewAdoption 创建一条领养记录
func CreateNewAdoption(newAdoption model.Adoption) error {
	err := initConfig.GormDb.Create(&newAdoption).Error
	if err != nil {
		zap.L().Error("无法在数据库中创建领养记录", zap.Error(err))
		return err
	}
	return nil
}

// UpdateAnimal 更新动物信息
func UpdateAnimal(animal *model.AnimalsInformation) error {
	err := initConfig.GormDb.Save(animal).Error
	if err != nil {
		zap.L().Error("无法更新动物状态信息" + err.Error())
		return err
	}
	return nil
}

// DeleteAnimalByID 删除动物
func DeleteAnimalByID(animalID string, isAdopted bool) error {
	// 在动物信息表中删除动物
	result := initConfig.GormDb.Where("id = ?", animalID).Delete(&model.AnimalsInformation{})
	if result.Error != nil {
		zap.L().Error("删除动物失败", zap.Error(result.Error))
		return result.Error
	}

	if isAdopted == true {
		result = initConfig.GormDb.Where("animal_id = ?", animalID).Delete(&model.Adoption{})
		if result.Error != nil {
			zap.L().Error("删除动物失败", zap.Error(result.Error))
			return result.Error
		}
	}

	return nil
}
